<template>
  <div>
    <p v-if="podMap.length == 1" class="pod-name">{{ podName }}</p>
    <el-select v-else v-model="podName" class="pod-name-select" placeholder="请选择" @change="selectPod">
      <el-option v-for="item in podMap" :key="item" :label="item" :value="item">
      </el-option>
    </el-select>
    <div class="monitoring" v-if="active == 1">
      <v-chart :option="gpuData" class="chart-item" />
      <v-chart :option="cpuData" class="chart-item" />
      <v-chart :option="memData" class="chart-item" />
    </div>
    <!-- <div class="log" v-if="active == 2">
      <ul ref="logBox" class="log-box">
        <li class="log-lis" v-for="(e, i) in logData" v-html="e" :key="i"></li>
      </ul>
    </div> -->
    <div class="metrics" v-if="active == 3">
      <div v-for="e in plots" :key="e.key" class="metrics-item">
        <metrics-chart-bar  :metricData="getMetricData" :option_cfg="e" v-if="e && e.value && e.plot_type == 'bar'" />
        <metrics-chart-pie :metricData="getMetricData" :option_cfg="e"  v-if="e && e.value && e.plot_type == 'pie'" />
        <metrics-chart-scatter :metricData="getMetricData" :option_cfg="e"  v-if="e && e.value && e.plot_type == 'scatter'" />
      </div>
      <div v-for="(e, i) in metrics" :key="i" class="metrics-item">
        <metrics-chart :metricData="getMetricData" :option_cfg="e" v-if="e" />
      </div>
      
    </div>
  </div>
</template>

<script>

import { getexperimentPodName, metricKeys, metricData } from '@/api/notebook'
import { usageDuration, myNamespace } from '@/api/dashboard'
import metricsChart from '@/components/module/metrics-chart'
import metricsChartBar from '@/components/module/metrics-chart-bar'
import metricsChartPie from '@/components/module/metrics-chart-pie'
import metricsChartScatter from '@/components/module/metrics-chart-scatter'
import { formatTime } from "@/utils/tool";
export default {
  data () {
    return {
      podName: '',
      podMap: [],
      gpuData: {},
      cpuData: {},
      memData: {},
      logSocket: null,
      logMsg: null,
      logData: [],
      metrics: [],
      plots: []
    };
  },
  props:["active"],
  components: {
    metricsChart,
    metricsChartBar,
    metricsChartPie,
    metricsChartScatter
  },
  watch: {
    active(val) {
      this.monitor(val)
    }
  },
  methods: {
    monitor(val){
      if (val == 1) {
        this.renderMonitoring()
      }
      if (val == 2) {
        this.renderLog(this.podName)
      }
      if (val == 3) {
        this.renderMetric()
      }
    },
    async getPod() {
      let res = await getexperimentPodName({ id: this.$route.query.id })
      if (!res || !res.data) {
        return;
      }
      this.podName = res.data[0]
      this.podMap = res.data
    },
    async getMetricData(id,key,type){
      let ret= await metricData({ id: id, key:key, type:type })
      return ret
    },
    async getduration(pod_name, resource_type) {
      return await usageDuration({
        end: formatTime(new Date().getTime()),
        pod_name,
        resource_type,
        start: formatTime(new Date().getTime() - 1000 * 60 * 60 * 1),
        step: "15s",
      })
    },
    selectPod() {
      this.monitor(this.active)
    },
    async renderMonitoring() {
      if (!this.podName) {
        return;
      }
      let gpu = await this.getduration(this.podName, 'gpu')
      let cpu = await this.getduration(this.podName, 'cpu')
      let mem = await this.getduration(this.podName, 'mem')
      gpu.data.color = [
        'rgb(255, 70, 131)',
        'rgb(255, 158, 68)',
        'rgb(255, 70, 131)'
      ]
      cpu.data.color = [
        'rgb(255, 70, 131)',
        'rgb(255, 158, 68)',
        'rgb(255, 70, 131)'
      ]
      mem.data.color = [
        'rgb(255, 70, 131)',
        'rgb(255, 158, 68)',
        'rgb(255, 70, 131)'
      ]
      gpu.data.title = 'GPU'
      cpu.data.title = 'CPU'
      mem.data.title = 'MEM'
      this.gpuData = gpu.data
      this.cpuData = cpu.data
      this.memData = mem.data
    },
    toBottom () {
      let sH = this.$refs.logBox && this.$refs.logBox.scrollHeight;
      let sT = this.$refs.logBox && this.$refs.logBox.scrollTop;
      let oH = this.$refs.logBox && this.$refs.logBox.offsetHeight;
      if (sH - sT < oH + 40) {
        this.$refs.logBox.scrollTop = this.$refs.logBox.scrollHeight;
      } else {
        console.log(
          "断掉数据push，并且存储到临时容器。 当滚动条滚动到底部的时候 再把临时数据塞进正常ui"
        );
      }
    },
    msgFn(e) {
      if (e.data == "ws message received") return;
      console.log(e.data)
      if (this.logData.length > this.num * 30) {
        this.logData.shift();
        this.logData.push(e.data.replace(/\n/g, "<br />"));
      } else {
        this.logData.push(e.data.replace(/\n/g, "<br />"));
      }
      this.toBottom();
    },
    async renderLog(podName) {
      console.log(podName)
      this.logData = []
      this.logMsg && this.logMsg.disconnect();
      let res = await this.$myInfo(this)
      console.log(await myNamespace())
      let namespaceReg = await myNamespace()
      let containerName = podName.search("-jupyter-") != -1 ? 'jupyter' : 'webide';
      this.logMsg = new this.$ws({ url: `cloud/ws/logwatch/${res.id}/${ namespaceReg.data }/${this.podName}/${containerName}` })
      this.logMsg.initWebSocket(this.msgFn)
    },
    recursion(arr, fn, doSomething) {
      let i = 0
      let rec = async e => {
        if (i > arr.length - 1) return
        let res = await fn(e)
        console.log(res)
        doSomething(e, res)
        i ++ 
        rec(arr[i])
      }
      rec(arr[i])
    },
    async renderMetric() {
      this.metrics = []
      let metricsKey = await metricKeys({ id: this.$route.query.id, type: 'metrics' })
      let plotsKey = await metricKeys({ id: this.$route.query.id, type: 'plots' })
      metricsKey.data.forEach(async e => {
        let option_cfg ={
          id :this.$route.query.id,
          key: e,
          type: 'metrics'
        }
        this.metrics.push(option_cfg)
      })
      this.plots =[]
      plotsKey.data.forEach(async e => {
        let ret = await metricData({ id: this.$route.query.id, key: e, type: 'plots' })
        let item = ret.data[0]
        let option_cfg ={
          id :this.$route.query.id,
          key: e,
          type: 'plots',
          value: item.value,
          plot_type: item.plot_type
        }
        this.plots.push(option_cfg)
      })
      // this.metrics.push({
      //     title: 'e',
      //     values: testData.data.map(e => [e.timestamp,  e.value, e.smooth - 0])
      //   })
      // this.recursion(metricsKey.data, async e => {
      //   return await metricData({ id: this.$route.query.id, key: e, type: 'metrics' })
      // }, (title, metric) => {
      //   console.log(title, metric)
      //   this.metrics.push({
      //     title: title,
      //     values: metric.data.map(e => [e.timestamp,  e.value, e.smooth - 0])
      //   })
      // })
      // metricsKey.data.forEach(async e => {
      //   let metric = await metricData({ id: this.$route.query.id, key: e, type: 'metrics' })
      //   console.log(testData)
      //   this.metrics.push({
      //     title: e,
      //     values: metric.data.map(e => [e.timestamp,  e.value, e.smooth - 0])
      //   })
      // })
      // this.plots =[]
      // this.recursion(plots.data, async e => {
      //   return await metricData({ id: this.$route.query.id, key: e, type: 'plots' })
      // }, (e, plots) => {
      //   plots.data.forEach(item => {
      //     this.plots.push(item)
      //   })
      // })
      // plots.data.forEach(async e => {
      //   let plots = await metricData({ id: this.$route.query.id, key: e, type: 'plots' })
      //   plots.data.forEach(e => {
      //     this.plots.push(e)
      //   })
      // })
    }
  },
  async mounted() {
    await this.getPod()
    this.selectPod()    
  }
}
</script>
<style lang="less" scoped>
.chart-item{
  height: 320px;
}
.log{
  background: #000;
  padding: 20px;
  margin: 20px 0 0;
  box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.6);
  min-height: 400px;
  .log-box{
    overflow-x: hidden;
    overflow-y: auto;
    padding-right: 10px;
    .log-lis {
      color: #999;
      font-size: 12px;
    }
  }
}
.metrics{
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  .metrics-item{
    width: 50%;
    height: 400px;
  }
}
</style>